#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Farmer Li
# @Date: 2021-09-26
# @Question: https://www.zhihu.com/question/489087749

from pathlib import Path

from PIL import Image
import click

# 二维码模板左上角坐标
QR_CODE_UPPER_LEFT = (300, 290)

# 二维码模板中放置二维码的区域大小
QR_CODE_SIZE = (360, 360)


def add_qr_code_to_template_and_save(t_img: Image.Image, qr_img: Image.Image,
                                     save_path: Path):
    target_img = t_img.convert('RGBA')

    # resize
    qr_img = qr_img.resize(QR_CODE_SIZE, Image.ANTIALIAS)

    # Paste qr code to tamplate
    target_img.paste(qr_img, QR_CODE_UPPER_LEFT, mask=None)

    target_img.save(save_path)


def process(template_path: Path, qr_code_dir: Path, save_dir: Path):
    if not template_path.exists():
        return
    if not qr_code_dir.exists() or not qr_code_dir.is_dir():
        return

    save_dir.mkdir(parents=True, exist_ok=True)

    t_img = Image.open(template_path)

    for f in qr_code_dir.iterdir():
        if not f.is_file():
            continue

        print(f'Processing {f}')
        qr_img = Image.open(f)

        save_path = save_dir / f'{f.name}'

        add_qr_code_to_template_and_save(t_img, qr_img, save_path)


@click.command()
@click.argument('template-img', type=Path)
@click.argument('qr-code-dir', type=Path)
@click.argument('save_dir', type=Path)
def main(template_img, qr_code_dir, save_dir):
    process(template_img, qr_code_dir, save_dir)


if __name__ == '__main__':
    main()
